//
//  ToDoListAppDelegate.m
//  ToDoList
//
// This code file is apart of project "iPhone-ToDo-List" 
// (http://code.google.com/p/iphone-todo-list/)
//
// Copyright (c) 2009 Frank Villasenor
//
// Distributed under the terms of the Lesser GNU General Public License.
// A copy of the license should be with these files. If not, you 
// can retrieve a copy from http://www.gnu.org/licenses/lgpl-3.0.txt
// 

#import "ToDoListAppDelegate.h"

#import "Constants.h"

@implementation ToDoListAppDelegate


@synthesize window;
@synthesize mainNavController;
@synthesize taskList;


- (void)dealloc 
{
	[mainNavController release];
	[taskList release];
	
    [window release];
    [super dealloc];
}


- (void)applicationDidFinishLaunching:(UIApplication *)application
{    
	//
	// Load the file and assign it to taskList.
	NSString *filePath = [self dataFilePath];
	if( [[NSFileManager defaultManager] fileExistsAtPath:filePath] )
	{
		NSData *data = [[NSData alloc] initWithContentsOfFile:[self dataFilePath]];
		NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
		
		self.taskList = [unarchiver decodeObjectForKey:kDataKey];
		[unarchiver finishDecoding];
		
		[unarchiver release];
		[data release];
	}
	else
	{
		NSMutableArray *localTaskList = [[NSMutableArray alloc] initWithCapacity:1];
		self.taskList = localTaskList;
		[localTaskList release];
	}
	
	[window addSubview:mainNavController.view];
	
	
    // Override point for customization after application launch
    [window makeKeyAndVisible];
}

- (void)applicationWillTerminate:(UIApplication *)application
{
	[self saveTaskListToDataFile];
}

#pragma mark -
#pragma mark Custom Methods

- (void)saveTaskListToDataFile
{
	NSMutableData *data = [[NSMutableData alloc] init];
	NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
	
	[archiver encodeObject:self.taskList forKey:kDataKey];
	[archiver finishEncoding];
	
	[data writeToFile:[self dataFilePath] atomically:YES];
	
	[archiver release];
	[data release];
}

//
// Taken from the Persistence Application (PersistenceViewController.m)
//  Chp. 11; pg. 335. (both: dataFilePath & applicationWillTerminate:
- (NSString *)dataFilePath
{
	NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES );
	NSString *documentsDirectory = [paths objectAtIndex:0];
	return [documentsDirectory stringByAppendingPathComponent:kVersion1FileName];
}

@end
